<?php
class Push_model extends CI_Model {
	private static  $read_db=null;	
	/**
	 * 获取read_db的数据库连接
	 */
	private  function  read_db(){
		if(empty($read_db)){
			$read_db=$this->load->database('read_db', TRUE);
		}
		return $read_db;
	}
	
	public function __construct()
    {
        parent::__construct();
        $this->load->database();
    }

    /**
     * @param string $data
     * @result user
     */
    function carNumIsset($data){
    	try {
			if(empty($data)){
				return false;
			}
			$query = $this->db->query('SELECT * FROM ca_device WHERE deviceNum='.$this->db->escape($data).' limit 1');
			$result = $query->row();
    	} catch (Exception $e) {
    		log_message('error',  $e->getMessage());
    	}
    	 return $result;
    }

    /**
     * @param string $uid
     * @result user
     */
    function getAll($uid){
    	try {
			$query = $this->db->query('select * from ca_device WHERE uid='.$this->db->escape($uid).' and status = 1 ');
			$result = $query->result_array();
    	} catch (Exception $e) {
    		log_message('error',  $e->getMessage());
    	}
    	 return $result;
    }

	/**
	 * @param string $id
	 * @result user
	 */
	function getOne($id){
		try {
			if(empty($id)){
				return false;
			}
			$query = $this->db->query('SELECT * FROM ca_device WHERE id='.$this->db->escape($id).' limit 1');
			$result = $query->row();
		} catch (Exception $e) {
			log_message('error',  $e->getMessage());
		}
		return $result;
	}

	/**
	 *
	 */
	function getUidByDeviceId($deviceId){
		try {
			if(empty($deviceId)){
				return false;
			}
			$query = $this->db->query('SELECT * FROM ca_device WHERE deviceNum='.$this->db->escape($deviceId).' limit 1');
			$result = $query->row();
		} catch (Exception $e) {
			log_message('error',  $e->getMessage());
		}
		return $result;
	}

	/**
	 * 获取我的圈发计划
	 * @param $uid
	 * @return bool
	 */
	function getMyAdPlan($uid){
		try {
			if(empty($uid)){
				return false;
			}
			$query = $this->db->query('SELECT * FROM ca_advertisement WHERE uid='.$this->db->escape($uid).' order by id desc');
			$result = $query->result_array();
		} catch (Exception $e) {
			log_message('error',  $e->getMessage());
		}
		return $result;
	}

	/**
	 * 获取我的圈发计划
	 * @param $uid	$cars
	 * @return bool
	 */
	function getRoundCars($data,$cars){
		try {
			if(empty($data)|| empty($cars)){
				return false;
			}
			$query = $this->db->query("select * from ca_long_lat where latitude<>0 and latitude>{$data['right-bottom']['lat']} and latitude<{$data['left-top']['lat']} and longitude>{$data['left-top']['lng']} and longitude<{$data['right-bottom']['lng']} group by device_id order by id desc limit ".$cars);
			$result = $query->result_array();
		} catch (Exception $e) {
			log_message('error',  $e->getMessage());
		}
		return $result;
	}


	/**
	 * 获取所有需要推送的广告
	 * @param $uid
	 * @return bool
	 */
	function getAllAd(){
		try {
			$time = time();
			$query = $this->db->query('SELECT * FROM ca_advertisement WHERE ad_begin_time<='.$time.' and ad_end_time>='.$time.' and status = 1 and times > 0');
			$result = $query->result_array();
		} catch (Exception $e) {
			log_message('error',  $e->getMessage());
		}
		return $result;
	}

	/**
	 * 添加推送广告结果记录
	 * @param $data
	 * @return bool
	 */
	function addPushAdRecord($data,$deviceId){
		try {
			$this->db->trans_strict(FALSE);
			$this->db->trans_begin();

			//写入广告推送记录
			$this->db->insert('ca_advertisement_push_record', $data);
			$adInsertId = $this->db->insert_id();
			if(empty($adInsertId)){$this->db->trans_rollback();return false;}

			if($data['status'] == 1){	//广告推送成功写入广告流水表、扣减广告余额表
				$time = time();
				//写入广告资金流水
				$insertOverFlow = array(
					'uid'=>$data['device_uid'],	//设备主人uid
					'cash'=>$data['cash'],
					'ad_id'=>$data['ad_id'],	//广告id
					'push_record_id'=>$adInsertId,	//广告推送记录id
					'status'=>$data['status']?:1,	//广告投送状态 1：成功  2：失败
					'create_time'=>$time,
					'update_time'=>$time
				);
				$this->db->insert('ca_advertisement_overflow', $insertOverFlow);		//插入资金流水记录表  ca_overflow
				$resultOverFlow = $this->db->insert_id();
				if(empty($resultOverFlow)){$this->db->trans_rollback();return false;}

				//扣减 ca_advertisement中的余额  扣减次数
				$this->db->query('update ca_advertisement set balance=balance-'.$this->db->escape($data['cash']).',times=times-1 where id='.$this->db->escape($data['ad_id']).' and balance >='.$this->db->escape($data['cash']).' and times > 0');
				$updateResult = $this->db->affected_rows();
				if($updateResult < 1){$this->db->trans_rollback();return false;}

				$uidPointArr = $this->getUidPointByDevice($deviceId);	//根据设备号获取用户uid及分成点
				if(empty($uidPointArr)){$this->db->trans_rollback();return false;}

				//写入资金流水
				$insertOverFlow = [];
				foreach ($uidPointArr as $uidPointRow){
					$insertOverFlow[] = array(
						'uid'=>$uidPointRow['uid'],	//设备主人uid
						'type'=>1,	//1:入账（充值、圈发播放广告收入）   2:出账（购买商品）
						'cash'=>$data['cash']*$uidPointRow['point'],
						'orderid'=>$adInsertId,		//这里是广告推送记录id
						'channel'=>'ad',	//来源 goods:购买商品  recharge:充值  withdraw:提现  ad：圈发   来源 1：购买商品  2：充值  3：提现  4：圈发
						'inputtime'=>$time,
						'updatetime'=>$time
					);

					//给设备主人添加余额
					$this->db->query('update ca_cbalance set balance=balance+'.$data['cash']*$uidPointRow['point'].' where uid='.$uidPointRow['uid']);
					$updateResult = $this->db->affected_rows();
					if($updateResult < 1){$this->db->trans_rollback();return false;}
				}

				$this->db->insert_batch('ca_overflow', $insertOverFlow);		//插入资金流水记录表  ca_overflow
//				$this->db->insert('ca_overflow', $insertOverFlow);		//插入资金流水记录表  ca_overflow
				$resultOverFlow = $this->db->insert_id();
				if(empty($resultOverFlow)){$this->db->trans_rollback();return false;}
			}
			$this->db->trans_commit();
		} catch (Exception $e) {
			$this->db->trans_rollback();
			log_message('error',  $e->getMessage());
		}
		return true;
	}

	/**
	 * 根据设备号获取用户uid及分成点
	 * @param $deviceId
	 * @return array
	 */
	public function getUidPointByDevice($deviceId)
	{
		$result = [];
		$devSql = "select uid,pid from `ca_device` where deviceNum='$deviceId'";
		$devQuery = $this->db->query($devSql);
		$devInfo = $devQuery->row();
		if(empty($devInfo->pid)){
			return $result;
		}
		//设备为平台所属
		if($devInfo->pid == 1){
			$result = [
				[
					'uid'=>$devInfo->uid,	//设备主人
					'point'=>0.5
				],
				[
					'uid'=>1,	//平台
					'point'=>0.5
				]
			];
			return $result;
		}

		$userSql = 'select u.userid,u.roleid,u.pid,c.uid from `ca_user` u LEFT JOIN ca_cusers c on u.phone=c.uname where u.userid='.$devInfo->pid;	//获取设备上级代理商信息
		$userQuery = $this->db->query($userSql);
		$userInfo = $userQuery->row();
		//设备为省级代理所属
		if($userInfo->roleid == 2){
			$result = [
				[
					'uid'=>$devInfo->uid,	//设备主人
					'point'=>0.5
				],
				[
					'uid'=>$userInfo->uid,	//所属代理商（省级）
					'point'=>0.3
				],
				[
					'uid'=>1,	//平台
					'point'=>0.2
				]
			];
		}elseif($userInfo->roleid == 3){	//设备为市级代理所属
			$pUserSql = 'select u.userid,u.roleid,u.pid,c.uid from `ca_user` u LEFT JOIN ca_cusers c on u.phone=c.uname where u.userid='.$userInfo->pid;	//获取市级代理商信息
			$pUserQuery = $this->db->query($pUserSql);
			$pUserInfo = $pUserQuery->row();
			$result = [
				[
					'uid'=>$devInfo->uid,	//设备主人
					'point'=>0.5
				],
				[
					'uid'=>$userInfo->uid,	//所属代理商（市级）
					'point'=>0.3
				],
				[
					'uid'=>$pUserInfo->uid,	//所属代理商（省级）
					'point'=>0.1
				],
				[
					'uid'=>1,	//平台
					'point'=>0.1
				]
			];
		}
		return $result;
	}




    
}